import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/17 20:33
 * @description 正序遍历
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.reverseWords("  hello world  ");
    }
    public String reverseWords(String s) {
        List<String> words = new ArrayList<>();
        int len = s.length(), r = 0;
        s = s + " ";
        while (r < len) {
            while (r < len && s.charAt(r) == ' ') {
                r++;
            }
            if (r == len) {
                break;
            }
            int l = r;
            while (r < len && s.charAt(r) != ' ') {
                r++;
            }
            words.add(s.substring(l, r));
        }
        int n = words.size();
        StringBuffer sb = new StringBuffer();
        for(int i = n - 1; i >= 0; i--) {
            sb.append(words.get(i) + " ");
        }
        return sb.substring(0, sb.length() - 1);
    }
}
